package com.sky.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dao.*;
import com.sky.entity.*;
import com.sky.exception.AddressException;
import com.sky.exception.CanCancelException;
import com.sky.exception.OrderBussnessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.StatisticVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Transactional
    public OrderSubmitVO submit(OrderDTO orderDTO) {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setId(orderDTO.getAddressBookId());
        List<AddressBook> list = addressBookMapper.list(addressBook);
        if (list.size() == 0 || list == null) {
            throw new AddressException(MessageConstant.ADDRESS_NOT_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList.size() == 0 || shoppingCartList == null) {
            throw new AddressException(MessageConstant.SHOPPING_CART_NOT_EMPTY);
        }
        Orders order = new Orders();
        BeanUtils.copyProperties(orderDTO, order);
        String estimatedDeliveryTime = orderDTO.getEstimatedDeliveryTime();
        //將estimatedDeliveryTime轉換為LocalDateTime格式
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parse = LocalDateTime.parse(estimatedDeliveryTime, pattern);
        order.setEstimatedDeliveryTime(parse);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setStatus(StatusConstant.WAIT_PAY);
        order.setUserId(userId);
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(StatusConstant.UNPAID);
        AddressBook addressBook1 = list.get(0);
        String phone = addressBook1.getPhone();
        order.setPhone(phone);
        order.setAddress(addressBook1.getDetail());
        order.setConsignee(addressBook1.getConsignee());
        order.setUserName(addressBook1.getConsignee());

        orderMapper.insert(order);


        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insert(orderDetailList);

        shoppingCartMapper.delete(userId);

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .orderTime(order.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    @Override
    public PageResult historyOrders(HistoryOrdersPageDTO historyOrdersPageDTO) {
        PageHelper.startPage(historyOrdersPageDTO.getPage(), historyOrdersPageDTO.getPageSize());
        OrderPageDTO orderPageDTO = new OrderPageDTO();
        orderPageDTO.setUserId(BaseContext.getCurrentId());
        orderPageDTO.setStatus(historyOrdersPageDTO.getStatus());

        Page<Orders> page = orderMapper.pageQuery(orderPageDTO);

        List<OrderVO> list = new ArrayList<>();

        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();

                List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(orderId);


                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public OrderVO orderDetail(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    /**
     * 支付订单
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 替代微信支付成功后的数据库订单状态更新，直接在这里更新了
        // 根据订单号查询当前用户的该订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());
        orderMapper.update(orders);
        return vo;
    }

    @Override
    public void paySuccess(String outTradeNo) {
        Long userId = BaseContext.getCurrentId();

        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    @Override
    public void cancel(CancelDTO cancelDTO) {
        // 根据订单id查询当前订单
        Orders orders = orderMapper.getById(cancelDTO.getId());
        if (cancelDTO.getCancelReason() == null || cancelDTO.getCancelReason() == "") {
            if (orders.getStatus() >= 4) {
                throw new CanCancelException(MessageConstant.CAN_NOT_CANCEL_ORDER);
            }
        }
        // 根据订单id更新订单的状态
        Orders order = new Orders();
        order.setId(cancelDTO.getId());
        order.setStatus(StatusConstant.CANCEL);
        order.setCancelTime(LocalDateTime.now());
        order.setCancelReason(cancelDTO.getCancelReason());
        orderMapper.update(order);
    }

    @Override
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);


    }

    @Override
    public PageResult conditionSearch(OrderQueryDTO orderQueryDTO) {
        PageHelper.startPage(orderQueryDTO.getPage(), orderQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.list(orderQueryDTO);
        List<OrderQueryVO> list = new ArrayList<>();
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();
                OrderQueryVO orderQueryVO = new OrderQueryVO();
                BeanUtils.copyProperties(orders, orderQueryVO);
                List<String> nameList = orderDetailMapper.getNameByOrderId(orderId);
                //在每個name後面加空格
                for (int i = 0; i < nameList.size(); i++) {
                    nameList.set(i, nameList.get(i) + "  ");
                }
                orderQueryVO.setOrderDishes(nameList);
                list.add(orderQueryVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public StatisticVO statistics() {
        //待派送的數量
        int confirmedCount = countByStatus(StatusConstant.RECEIVED);

        //派送中數量
        int deliveryInProgressCount = countByStatus(StatusConstant.DELIVERING);

        //待接單數量
        int toBeConfirmedCount = countByStatus(StatusConstant.WAIT_RECEIVE);

        StatisticVO statisticVO = new StatisticVO();
        statisticVO.setConfirmed(confirmedCount);
        statisticVO.setDeliveryInProgress(deliveryInProgressCount);
        statisticVO.setToBeConfirmed(toBeConfirmedCount);
        return statisticVO;

    }

    @Override
    public void confirm(ConfirmDTO confirmDTO) {
        Orders orders = new Orders();
        orders.setId(confirmDTO.getId());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(StatusConstant.RECEIVED);
        orderMapper.update(orders);
    }

    @Override
    public void rejection(RejectionDTO rejectionDTO) {
        Orders orders = new Orders();
        orders.setId(rejectionDTO.getId());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(StatusConstant.CANCEL);
        orders.setCancelTime(LocalDateTime.now());
        orders.setRejectionReason(rejectionDTO.getRejectionReason());
        orders.setCancelReason(rejectionDTO.getRejectionReason());
        orderMapper.update(orders);
    }

    private int countByStatus(int status) {
        int count = orderMapper.countByStatus(status);
        return count;
    }

    @Override
    public void delivery(Long id) {
        Orders orders = new Orders();
        orders.setUserId(BaseContext.getCurrentId());
        orders.setId(id);
        orders.setStatus(StatusConstant.DELIVERING);
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders orders = new Orders();
        orders.setUserId(BaseContext.getCurrentId());
        orders.setId(id);
        orders.setStatus(StatusConstant.FINISHED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
}

